package com.ionehe.group.common.uaa.ex.dto;

import cn.hutool.core.util.StrUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class ForestNodeMerger {
    public ForestNodeMerger() {
    }

    public static <T extends INode> List<T> merge(List<T> items) {
        ForestNodeManager<T> forestNodeManager = new ForestNodeManager(items);
        items.forEach((forestNode) -> {
            String parentId = forestNode.getParentId();
            if (!StrUtil.equals(parentId, "0") || !StrUtil.isEmpty(parentId)) {
                INode node = forestNodeManager.getTreeNodeAT(forestNode.getParentId());
                if (node != null) {
                    node.getChildren().add(forestNode);
                } else {
                    forestNodeManager.addParentId(forestNode.getId());
                }
            }

        });
        return forestNodeManager.getRoot();
    }

    public static List<Map<String, Object>> merge(List<Map<String, Object>> maps, String field, String parentfield) {
        maps.forEach((item) -> {
            List<Map<String, Object>> childMap = new ArrayList();
            item.put("children", childMap);
            if (!item.get(parentfield).toString().equals("0") || !StrUtil.isEmpty((CharSequence) item.get(parentfield))) {
                maps.forEach((it) -> {
                    if (it.get(field).toString().equals(item.get(parentfield).toString())) {
                        List<Map<String, Object>> children = (List)it.get("children");
                        if (children == null) {
                            children = new ArrayList();
                            it.put("children", children);
                        }

                        ((List)children).add(item);
                    }

                });
            }

        });
        List<Map<String, Object>> result = (List)maps.stream().filter((x) -> {
            return x.get(parentfield).equals("0") || StrUtil.isEmpty((CharSequence) x.get(parentfield));
        }).collect(Collectors.toList());
        return result;
    }
}
